# 导包
import pymysql
# 创建链接


class DBUtil:

    __conn = None
    __cursor = None
    # 创建链接

    @classmethod
    def __get_conn(cls):
        if cls.__conn is None:
            cls.__conn = pymysql.connect(host="127.0.0.1",port="3306",user="root",password="root",database="books")

        return cls.__conn
# 获取游标

    @classmethod
    def __getcursor(cls):
        # 调用获取连接方法
        if cls.__cursor is None:
            cls.__cursor = cls.__get_conn().cursor()
        return  cls.__cursor
# 执行sql

    @classmethod
    def exe_sql(cls,sql):
        try:
            # 获取游标对象方法
            cursor = cls.__getcursor()
            cursor.execute(sql)
            # 如果是查询
            if sql.split()[0].lower == "select":
                # 返回查询结果
                return  cursor.fetchall()
            # 否则
            else:
                # 提交事务
                cls.__conn.commit()
                # 返回受影响的行数
                return cursor.rowcount
        except Exception as e:
            # 抛出异常
            print(e)

            # 回滚事务
            cls.__conn.rollback()

        finally:
            # 关闭游标
            cls.__close_cursor()
            # 关闭连接
            cls.__close_conn()

# 关闭游标
    @classmethod
    def __close_cursor(cls):
        if cls.__cursor:
            cls.__cursor.close()


# 关闭连接
    @classmethod
    def __close_conn(cls):
        if cls.__conn:
            cls.__cursor.close()

